import { call, put, fork, select, take } from 'redux-saga/effects'
import { message } from 'antd'
import api from '@/api/whiteList'
import actions,{ GET_DATA, ADD_DATA, DELETE_DATA } from '@/actions/whiteList'
import util from '@/utils'
import successDesc from '@/constants/success'

function* getData() {
  try {
    const params = yield select(({ whiteListReducer }) => util.pick(whiteListReducer, [
      'pageNum',
      'pageSize',
      'phone',
      'startTime',
      'endTime',
    ]))
    const { startTime, endTime } = params       
    params.startTime = util.formatDay(startTime)
    params.endTime = util.formatDay(endTime)
    const { isSuccess, data, desc } = yield call(api.getWhiteListData, params)
    if(isSuccess && data && Array.isArray(data.list)){
      yield put(actions.getDataSuccess(data))
      //!data.size && message.warning(desc)
    }else{
      throw new Error(desc)
    }
  } catch (error) {
    yield put(actions.getDataFail())
    message.error(error.message || '获取数据错误')
  }
}

function* addData() {
  try {
    const params = yield select(({ whiteListReducer }) => ({
      phone: whiteListReducer.addPhone
    }))
    const { isSuccess, desc } = yield call(api.addWhiteListData, params)
    if(isSuccess){
      yield put(actions.addDataSuccess())
      message.success(successDesc.add)
      yield put(actions.hiddenAddModal())
      yield put(actions.getData())
    }else{
      throw new Error(desc)
    }
  } catch (error) {
    yield put(actions.addDataFail())
    message.error(error.message || '添加白名单错误')
  }
}

function* deleteData(params) {
  try {
    const { isSuccess, desc } = yield call(api.deleteWhiteListData, params)
    if(isSuccess){
      yield put(actions.deleteDataSuccess())
      message.success(successDesc.delete)
      yield put(actions.hiddenAddModal())
      yield put(actions.getData())
    }else{
      throw new Error(desc)
    }
  } catch (error) {
    yield put(actions.deleteDataFail())
    message.error(error.message || '删除白名单错误')
  }
}

function* watchDeleteData() {
  while(true) {
    const { data: { phone }} = yield take(DELETE_DATA)
    yield call(deleteData, { phone })
  }
}

function* watchAddData() {
  while (true) {
    yield take(ADD_DATA)
    yield call(addData)
  }
}

function* watchGetData() {
  while (true) {
    yield take(GET_DATA)
    yield call(getData)
  }
}

export default [
  fork(watchGetData),
  fork(watchAddData),
  fork(watchDeleteData),
]